<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { useArticleStore } from '@/stores/article'
import router from '@/router'
// 分类数据列表
const categoryList = ref([])
const useArticleStores = useArticleStore()
// 当前编辑的分类
const currentCategory = reactive({
    id: null,
    name: '',
    sort: 1
})
const pagination = ref({
    page: 1,
    pageSize: 10,
    total: 0,
})
// 是否显示对话框
const dialogVisible = ref(false)
const dialogTitle = ref('添加分类')

// 表单引用和验证规则
const formRef = ref(null)
const rules = {
    name: [
        { required: true, message: '请输入分类名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    sort: [
        { required: true, message: '请输入排序值', trigger: 'change' }
    ]
}

// 获取分类列表
const fetchCategories = async () => {

    const response = await useArticleStores.articleCategories();
    console.log('获取分类列表')

    // 模拟数据categoryList.value = response.sort((a, b) => a.sort - b.sort)
    categoryList.value = response.articlecategories.sort((a, b) => a.id - b.id)

    pagination.value = response.pagination
    console.log('后端返回的数据：', response.articlecategories)
}

// 打开添加对话框
const handleAdd = () => {
    currentCategory.id = null
    currentCategory.name = ''
    currentCategory.sort = 1
    dialogTitle.value = '添加分类'
    dialogVisible.value = true
}
function handleSizeChange(size) {
    pagination.pageSize = size;
    fetchCategories();
}

// 处理页码变化
function handlePageChange(page) {
    pagination.page = page;
    fetchCategories();
}
// 打开编辑对话框
const handleEdit = (row) => {
    currentCategory.id = row.id
    currentCategory.name = row.name
    currentCategory.sort = row.sort
    dialogTitle.value = '编辑分类'
    dialogVisible.value = true
}
const updateAt=ref()
// 确认添加/编辑
const confirmSubmit = () => {
    if (!formRef.value) return

    formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                if (!currentCategory.id) {
                    // 添加新分类
                    await useArticleStores.categoriesAdd({
                        name: currentCategory.name,
                        sort: currentCategory.sort
                    })
                    ElMessage.success('分类添加成功')
                } else {
                    // 编辑现有分类
                    await useArticleStores.categoriesUpdate(currentCategory.id, {
                        name: currentCategory.name,
                        sort: currentCategory.sort
                    })
                    ElMessage.success('分类更新成功')
                }

                // 无论添加还是编辑，都重新拉取数据
                await fetchCategories()
                dialogVisible.value = false
            } catch (error) {
                console.error('操作失败:', error)
                ElMessage.error('操作失败')
            }
        } else {
            return false
        }
    })
}
const formatDate = (time) => {
    if (!time) return '';
    const date = new Date(time);
    const beijingTime = new Date(date.getTime() + 8 * 3600 * 1000); // 转换为北京时间
    return beijingTime.toISOString().replace('T', ' ').substring(0, 19); // 格式化为 YYYY-MM-DD HH:MM:SS
};
// 确认删除√
const handleDelete = (row) => {
    ElMessageBox.confirm(
        `确定要删除分类 "${row.name}" 吗？`,
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {

        await useArticleStores.categoriesDelete(row.id);
        ElMessage.success('分类删除成功')
        fetchCategories()
    }).catch(() => { })
}

// 页面加载时获取数据
onMounted(() => {
    fetchCategories()
})

</script>

<template>
    <div class="category-container">

        <div class="header-actions">
            <el-button type="primary" :icon="Plus" @click="handleAdd">
                添加分类
            </el-button>
        </div>

            <el-table :data="categoryList" border style="width: 100%">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="name" label="分类名称" min-width="150" />
                <el-table-column label="创建时间" width="200">
                    <template #default="{ row }">
                        {{ formatDate(row.createdAt) }}
                    </template>
                </el-table-column>
                <el-table-column label="修改时间" width="200">
                    <template>
                        {{ formatDate(updateAt) }}
                    </template>
                </el-table-column>
                <el-table-column prop="sort" label="排序" width="100" />
                <el-table-column label="操作" width="180">
                    <template #default="{ row }">
                        <el-button link type="primary" :icon="Edit" @click="handleEdit(row)">
                            编辑
                        </el-button>
                        <el-button link type="danger" :icon="Delete" @click="handleDelete(row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
     
        <!-- 分页组件 -->
        <!-- <div class="pagination-container">
            <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 50, 100]" :layout="'total, sizes, prev, pager, next, jumper'"
                :total="pagination.total" @size-change="handleSizeChange" @current-change="handlePageChange" />
        </div> -->
        <!-- 分类表单对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
            <el-form ref="formRef" :model="currentCategory" label-width="100px" :rules="rules">
                <el-form-item label="分类名称" prop="name">
                    <el-input v-model="currentCategory.name" placeholder="请输入分类名称" />
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="currentCategory.sort" :min="1" :max="999" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmSubmit">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
     <div class="header-actions">
            <el-button type="primary"  @click="router.push('/content/articles')">
                返回文章列表
            </el-button>
        </div>
</template>

<style scoped>
.category-container {
    padding: 20px;
}

.header-actions {
    margin-bottom: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>